package com.xtayfjpk.zookeeper.test.master_workers.callback.master;

import org.apache.log4j.Logger;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.KeeperException.Code;

import com.xtayfjpk.zookeeper.test.master_workers.Master;
import com.xtayfjpk.zookeeper.test.master_workers.callback.BaseStringCallback;

public class AssignTaskCallback extends BaseStringCallback {
	private static final Logger LOGGER = Logger.getLogger(AssignTaskCallback.class);
	private Master master;
	
	public AssignTaskCallback(Master master) {
		this.master = master;
	}
	
	@Override
	protected void connectionLossCaseAction(int rc, String path, Object ctx, String name) {
		master.createAssignment(path, (byte[])ctx);
	}
	
	@Override
	protected void okCaseAction(int rc, String path, Object ctx, String name) {
		LOGGER.info("Task assigned correctly: " + name);
		//当待执行任务分配完成后，则需要将其在待执行任务列表中移除
		master.deleteTask(name.substring(name.lastIndexOf("/")+1));
	}
	
	@Override
	protected void nodeExistsCaseAction(int rc, String path, Object ctx, String name) {
		LOGGER.warn("Task:" +path+ " already assigned");
	}
	
	@Override
	protected void defaultCaseAction(int rc, String path, Object ctx, String name) {
		LOGGER.error("Error when trying to assign task.", 
                KeeperException.create(Code.get(rc), path));
	}
}
